package cn.yusei.teamTribe.controller.team;

import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import cn.yusei.teamTribe.constant.PermissionType;
import cn.yusei.teamTribe.constant.ResponseCode;
import cn.yusei.teamTribe.constant.TextType;
import cn.yusei.teamTribe.entity.Team;
import cn.yusei.teamTribe.service.PermissionService;
import cn.yusei.teamTribe.service.TextFilterService;
import cn.yusei.teamTribe.service.team.TeamService;
import cn.yusei.teamTribe.util.ResponseUtil;

@Controller
public class TeamController {

	@Autowired
	private TeamService teamService;
	@Autowired
	private PermissionService permissionService;
	@Autowired
	private TextFilterService textFilterService;
	@Value("${maxNameLength}")
	private int maxNameLength;
	
	@RequestMapping(value = "/team/add",method = RequestMethod.POST)
	public void add(@RequestAttribute("id")int id, @RequestParam int masterId, Team team,PrintWriter out){
		team.setName(textFilterService.getFilterString(team.getName(), TextType.TEAM_INFO));
		team.setComment(textFilterService.getFilterString(team.getComment(), TextType.TEAM_INFO));
		if(masterId <= 0 || !team.isInsertValid()){
			ResponseUtil.responseCode(out, ResponseCode.PARAM_ILLEGAL);
			return;
		}
		if(!permissionService.havePermission(id, team.getSchoolId(), PermissionType.ADD_TEAM, 1)){
			ResponseUtil.responseCode(out, ResponseCode.PERMISSION_FORBIDDEN);
			return;
		}
		int code;
		try {
			code = teamService.add(masterId, team);
		} catch (Exception e) {
			e.printStackTrace();
			ResponseUtil.responseCode(out,ResponseCode.SERVER_ERROR);
			return;
		}
		ResponseUtil.responseCode(out, code);
		
	}
	
	/**
	 * 获取满足条件的团队种类
	 * schoolId 和 tagId  至少要有一个
	 * @param schoolId
	 * @param tagId
	 * @param out
	 */
	@RequestMapping(value="/team/get")
	public void get(@RequestParam(defaultValue="0") int schoolId, @RequestParam(defaultValue="0") int tagId, PrintWriter out)
	{
		if(schoolId < 0 || tagId < 0 || (schoolId == 0 && tagId == 0))
		{
			ResponseUtil.responseCode(out, ResponseCode.PARAM_ILLEGAL);
			return;
		}
		Set<Integer> ids = null;
		try
		{
			ids = teamService.get(schoolId, tagId);
		}
		catch (Exception e)
		{
			e.printStackTrace();
			ResponseUtil.responseCode(out, ResponseCode.SERVER_ERROR);
			return;
		}
		Map<String, Object> param = new HashMap<String, Object>();
		param.put("ids", ids);
		ResponseUtil.response(out, ResponseCode.REQUEST_SUCCESSED, param);
	}
	
}
